package com.hmall.search.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;

import co.elastic.clients.json.JsonData;
import com.hmall.api.domain.dto.ItemDTO;
import com.hmall.api.domain.query.ItemPageQuery;
import com.hmall.common.domain.PageDTO;

import com.hmall.search.domain.dto.ItemDoc;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
@Slf4j
public class SearchController {

    private final ElasticsearchClient elasticsearchClient;

    @Operation(description = "搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDTO> search(ItemPageQuery query) throws IOException {
        // 构建查询条件
        SearchRequest searchRequest = buildSearchRequest(query);

        // 执行搜索
        SearchResponse<ItemDoc> response = elasticsearchClient.search(searchRequest, ItemDoc.class);

        // 处理响应结果
        List<ItemDoc> items = response.hits().hits().stream()
                .map(Hit::source)
                .collect(Collectors.toList());

        // 转换为ItemDTO
        List<ItemDTO> itemDTOs = items.stream()
                .map(item -> BeanUtil.toBean(item, ItemDTO.class))
                .collect(Collectors.toList());

        // 返回分页结果
        return new PageDTO<>(response.hits().total().value(), itemDTOs);
    }


    private SearchRequest buildSearchRequest(ItemPageQuery query) {
        // 构建布尔查询
        Query boolQuery = QueryBuilders.bool(b -> {
            // 关键字搜索
            if (StrUtil.isNotBlank(query.getKey())) {
                b.must(m -> m.match(mt -> mt.field("name").query(query.getKey())));
            }
            // 品牌筛选
            if (StrUtil.isNotBlank(query.getBrand())) {
                b.filter(f -> f.term(t -> t.field("brand").value(query.getBrand())));
            }
            // 类目筛选
            if (StrUtil.isNotBlank(query.getCategory())) {
                b.filter(f -> f.term(t -> t.field("category").value(query.getCategory())));
            }
            // 价格区间筛选
            if (query.getMinPrice() != null || query.getMaxPrice() != null) {
                b.filter(f -> f.range(r -> {
                    r.field("price");
                    if (query.getMinPrice() != null) {
                        r.gte(JsonData.of(query.getMinPrice()));
                    }
                    if (query.getMaxPrice() != null) {
                        r.lte(JsonData.of(query.getMaxPrice()));
                    }
                    return r;
                }));
            }
            return b;
        });

        // 构建搜索请求
        return SearchRequest.of(s -> s
                .index("items")
                .query(boolQuery)
                .from((query.getPageNo() - 1) * query.getPageSize())
                .size(query.getPageSize()));
    }
}
